{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dfbb2e69",
   "metadata": {},
   "source": [
    "# Where\n",
    "\n",
    "### VOC模式\n",
    "\n",
    "转化成VOC数据格式的数据集,这部分数据是使用labelme进行标注的数据结果。\n",
    "\n",
    "```python\n",
    "def obj_convert2voc(input_dir: str, save_dir: str, labels: List[str] = None, partition: List[float] = [0.8, 0.2],\n",
    "                    noviz: bool = False, recursive: bool = True):\n",
    "    \"\"\"\n",
    "    Convert labelme format annotation to onekey_algo training dataset.\n",
    "\n",
    "    Args:\n",
    "        input_dir: str, input dir\n",
    "        save_dir: str, output dir\n",
    "        labels: str, labels file which contains labels of this dataset.\n",
    "        partition: float list, train, valid, test partition.\n",
    "        noviz: bool, viz or not.\n",
    "\n",
    "    Returns:\n",
    "\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b7bdade",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\n",
    "\n",
    "from onekey_algo.scripts.core import obj_convert2voc\n",
    "\n",
    "input_dir = r'C:\\Users\\onekey\\Project\\OnekeyDS\\skin4obj'\n",
    "save_dir = r'C:\\Users\\onekey\\Project\\OnekeyDS\\skin4obj_out'\n",
    "partition = [0.7, 0.3]\n",
    "viz = True\n",
    "\n",
    "obj_convert2voc(input_dir, save_dir = save_dir, partition = partition, noviz= not viz)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e74379f",
   "metadata": {},
   "source": [
    "### 支持的模型名称\n",
    "\n",
    "模型名称替换代码中的 `model_name`变量的值。\n",
    "\n",
    "| **模型系列** | **模型名称**                                                 |\n",
    "| ------------ | ------------------------------------------------------------ |\n",
    "| FasterRCNN      | fasterrcnn_resnet50_fpn, fasterrcnn_mobilenet_v3_large_320_fpn, fasterrcnn_mobilenet_v3_large_fpn        |\n",
    "| MaskRCNN          | maskrcnn_resnet50_fpn|\n",
    "| SSD       | ssd300_vgg16 |\n",
    "| Retinanet     | retinanet_resnet50_fpn           |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "83c24463",
   "metadata": {},
   "outputs": [],
   "source": [
    "from onekey_algo.detection.run_detection import main as dect_main\n",
    "\n",
    "# 如果自己有coco格式的数据，可以直接使用自己的目录。\n",
    "my_dir = r'C:\\Users\\onekey\\Project\\OnekeyDS\\skin4obj_out'\n",
    "model_name = 'fasterrcnn_resnet50_fpn'\n",
    "# 设置参数\n",
    "class params:\n",
    "    dataset = r'xxx_voc_fmt'\n",
    "    data_path = my_dir\n",
    "    model = model_name\n",
    "    lr = 0.02\n",
    "    lr_step_size = 8\n",
    "    lr_steps = [16, 22]\n",
    "    lr_gamma = 0.1\n",
    "    workers = 4\n",
    "    batch_size = 2\n",
    "    print_freq = 10\n",
    "    epochs = 26\n",
    "    optimizer = 'sgd'\n",
    "    momentum = 0.9\n",
    "    weight_decay = 1e-4\n",
    "    save_dir = os.path.join(my_dir, 'models')\n",
    "    resume = r''\n",
    "    save_per_epoch = False\n",
    "    start_epoch = 0\n",
    "    aspect_ratio_group_factor = 3\n",
    "    rpn_score_thresh = None\n",
    "    trainable_backbone_layers = None\n",
    "    data_augmentation = 'hflip'\n",
    "    \n",
    "    dist_url = 'env://'\n",
    "    world_size = 1\n",
    "    test_only = False\n",
    "    pretrained = True\n",
    "    add_date = False\n",
    "    \n",
    "    attr = {}\n",
    "\n",
    "    def __setattr__(self, key, value):\n",
    "        self.attr[key] = value\n",
    "\n",
    "# 训练模型\n",
    "dect_main(params)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "188d8ee9",
   "metadata": {},
   "source": [
    "### 批量预测\n",
    "\n",
    "批量进行数据预测，输出的结果左侧为原始数据，右侧为识别结果。\n",
    "\n",
    "* model_root：模型保存的路径，需要具体到viz目录，\n",
    "   > 例如`model_root = r'path2your_model_root\\20220601\\deeplabv3_resnet101\\viz'`\n",
    "   \n",
    "* test_samples：需要测试的样本集合\n",
    "   > 例如我们测试所有的val数据集的结果，`test_samples = glob.glob(os.path.join(save_dir, 'val', 'JPEGImages', '*.jpg'))`\n",
    "   \n",
    "* save_dir：测试结果输出目录，自己可以按需指定。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03b274ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "import glob\n",
    "import os\n",
    "from onekey_algo.detection.eval_detection import init, inference\n",
    "\n",
    "save_dir = r'C:/Users/onekey/Project/OnekeyDS/skin4obj_out/'\n",
    "model_root = os.path.join(my_dir, 'models', model_name)\n",
    "test_samples = glob.glob(os.path.join(save_dir, 'val', 'JPEGImages', '*.jpg'))\n",
    "save_dir = os.path.join(save_dir, 'val', 'test_results')\n",
    "\n",
    "model, class_names, device = init(model_root)\n",
    "inference(test_samples, model, device=device, class_names=class_names, save_dir=save_dir)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02d4de3e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
